package com.pinkpig.excel.metadata.config;

import org.mybatis.generator.config.JDBCConnectionConfiguration;
import org.mybatis.generator.internal.JDBCConnectionFactory;

import java.sql.*;

/**
 * @author fengs
 */
public class DatabaseConfiguration {

    private DatabaseMetaData metaData;

    private Connection connection;

    private JDBCConnectionFactory jdbcConnectionFactory;

    private Statement stmt;


    public DatabaseConfiguration(String userId, String password, String connectionURL, String driverClass){
        jdbcConnectionFactory = createJdbcConnectionFactory(userId, password, connectionURL, driverClass);

    }

    private JDBCConnectionFactory createJdbcConnectionFactory(String userId, String password, String connectionURL, String driverClass){
        JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
        jdbcConnectionConfiguration.setUserId(userId);
        jdbcConnectionConfiguration.setPassword(password);
        jdbcConnectionConfiguration.setConnectionURL(connectionURL);
        jdbcConnectionConfiguration.setDriverClass(driverClass);
        jdbcConnectionConfiguration.addProperty("useInformationSchema", "true");
        return new JDBCConnectionFactory(jdbcConnectionConfiguration);
    }

    public Connection getConnection() throws SQLException {
        if(null==connection){
            connection = jdbcConnectionFactory.getConnection();
        }
        return connection;
    }

    public DatabaseMetaData getMetaData() throws SQLException{
        if(null==metaData){
            metaData = getConnection().getMetaData();
        }
        return metaData;
    }

    public ResultSet getColumns(String tableName) throws SQLException {
        if (null == stmt) {
            stmt = getConnection().createStatement();
        }
        String queryColumnsSql = "select * from information_schema.COLUMNS where table_schema = database() and table_name = '" + tableName + "'";
        ResultSet rs = stmt.executeQuery(queryColumnsSql);
        return rs;
    }
}
